//	Author: EJS
//	This file contains the main features of the engine

/*
 * State functions:
 * We use cookies to save the state of the adventure. Develeopers may choose to
 * upload these cookies to a server if they dont want "clearing browser data" to
 * potentially erase all state data on RPDroid.
 * The names of these cookies will be:
 * 		stateCookie1,
 * 		stateCookie2,
 * 		....
 * 		stateCookieN
 * 	where N stands for the state number.
 * 
 * The formula which the values of these cookies are written in is:
 * 	currentScreen,itemList[0],itemList[1],...,itemList[N-1]
 * 
 */

function saveState(stateNr) {
	var name = "stateCookie" + stateNr.toString();
	var value = (game.currentScreen).toString();
	for (item in game.itemList) {
		value += "," + item.toString();
	}
	var days = 365;
	createCookie(name,value,days);
}

function loadState(stateNr) {
	var name = "stateCookie";
	name = name.concat(stateNr.toString());
	var value = readCookie(name);
	var arr = value.split(",");
	game.currentScreen = arr.pop();
	game.itemList = arr;
	loadScreen(game.currentScreen);
	hidePopup();
}

function deleteState(stateNr) {
	eraseCookie("stateCookie"+stateNr.toString());
}

// Imported cookie methods:
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name){
	createCookie(name,"",-1);
}

// Item methods
function addItem(itemId) {
	if($.inArray(itemId, game.playerInventory)==-1)
		game.playerInventory.push(itemId);
}

function removeItem(itemId) {
	var index = game.playerInventory.indexOf(itemId);
	game.playerInventory.splice(index,1);
}

function hasItem(itemId) {
	if($.inArray(itemId, game.playerInventory)==-1)
		return false;
	else
		return true;
}

// Progression methods
function calcProgression() {
	// Compares number of completed logs to the value of maxLogs
	var nrOfCompleted = 0;
	for(i=0; i<game.journalLogs.length; i++) {
		if( game.journalLogs[i].completed == true)
		nrOfCompleted++;
	}
	return Math.round(100*(nrOfCompleted/game.journalLogs.length)) + "%";
}

// Interface methods
function popup() {
	$('div#popup').empty().fadeIn("fast")
	$('div#popup').append($('<img/>',{
		src: "img/close.png",
		style: "position: absolute;left: -20px;top: -20px; cursor: pointer",
		onclick: "javascript:hidePopup();"
	}))
}
function showInventory() {
	popup()
	$('div#popup').append($('<div/>', {
		style: "display: table; padding: 30px",
		id : "table"
	}))
	var empty = true
	$.each(game.items, function(key, item) {
		if(item.playerHasItem) {
			empty = false
			$('div#table').append($('<div/>', {
				id: "tablerow"+key,
				style: "display: table-row"
			}))
			$('div#tablerow'+key).append($('<div/>',{
				style: "display: table-cell",
			}).append($("<img/>",{
				src: "game/img/"+item.itemImage,
				width: "64px"
			})))
			$('div#tablerow'+key).append($('<div/>',{
				style: "display: table-cell",
			}).append($('<span/>',{
				text: item.itemDescription,
				style: "margin-left: 20px; position: relative; bottom: 50px;"
			})))
		}
	})
	if(empty) {
		$('div#table').append($('<div/>', {
			style: "text-align: center; font-size: 2em;",
			text: "No items in inventory!"
		}))
	}
}

function showJournal() {
	popup()
	$('div#popup').append($('<div/>', {
		style: "display: table; padding: 30px",
		id : "table"
	}))
	var empty = true
	$.each(game.journalLogs, function(key, journalLog) {
		if(journalLog.playerHasJournalLog) {
			empty = false
			$('div#table').append($('<div/>', {
				id: "tablerow"+key,
				style: "display: table-row"
			}))
			$('div#tablerow'+key).append($('<div/>',{
				style: "display: table-cell; font-size: 4em; white-space:nowrap",
				text: key+1+"  "
			}))
			$('div#tablerow'+key).append($('<div/>',{
				style: "display: table-cell",
			}).append($('<span/>',{
				id: "logDescription"+key,
				text: journalLog.logDescription,
				style: "margin-left: 20px; position: relative; bottom: 25px;"
			})))
			if(journalLog.completed) {
				$('span#logDescription'+key).css({
					"text-decoration": "line-through"
				})
			}
		}
	})
	if(empty) {
		$('div#table').append($('<div/>', {
			style: "text-align: center; font-size: 2em;",
			text: "No logs in journal!"
		}))
	}
}

function showStateMenu() {
	popup()
	$('div#popup').append($('<div/>', {
		style: "display: table; padding: 30px",
		id : "table"
	}))
	for(var key = 1; key!=5; key++) {
		//Add a table row
		$('div#table').append($('<div/>', {
			id: "tablerow"+key,
			style: "display: table-row"
		}))
		
		//Add items to the new row
		
		//State number
		$('div#tablerow'+key).append($('<div/>',{
			style: "display: table-cell; font-size: 4em; white-space:nowrap",
			text: key+"  "
		}))
		
		//State description
		$('div#tablerow'+key).append($('<div/>',{
			style: "display: table-cell",
		}).append($('<span/>',{
			id: "logDescription"+key,
			text: "Savegame "+key,
			style: "margin-left: 20px; position: relative; bottom: 25px;"
		})))
		
		//Save button
		$('div#tablerow'+key).append($('<div/>',{
			style: "display: table-cell",
		}).append($('<button/>',{
			text: "Save",
			onclick: "javascript:saveState("+key+")",
			style: "margin-left: 20px; position: relative; bottom: 25px;"
		})))
		
		//Load button
		$('div#tablerow'+key).append($('<div/>',{
			style: "display: table-cell",
		}).append($('<button/>',{
			text: "Load",
			onclick: "javascript:loadState("+key+")",
			style: "margin-left: 20px; position: relative; bottom: 25px;"
		})))
	}
}


function showWorldmap() {
	popup()
	$('div#popup').append(
		$('<img/>', {
			id: "worldMap",
			style: "width: 600px; height: 600px;",
			src: "game/img/"+game.worldmap
		})
	)
	$.each(game.screenList, function(key, screen) {
		if(!screen.coordinates) {
			return true
		}
		if(screen.screenId == game.currentScreen) {
			$('div#popup').append($('<img/>',{
				style: "position: absolute; left: "+screen.coordinates[0]+"px; top: "+screen.coordinates[1]+"px;",
				src: "img/here.png"
			}))
		} else {
			$('div#popup').append($('<img/>',{
				style: "position: absolute; left: "+screen.coordinates[0]+"px; top: "+screen.coordinates[1]+"px;",
				src: "img/marker.png"
			}))
		}
	})
}

function showProgression() {
	
	$('div#currentProgression').text(calcProgression())
	$('div#currentProgression').show("fast")
	setTimeout("$('div#currentProgression').hide('fast')",2000)
}

function hidePopup() {
	$('div#popup').fadeOut("fast")
}

// Main methods
function loadScreen(screenID) {
	//Maintains our currentScreen for load/save purposes
	game.currentScreen = screenID
	
	//Displays the title of the current screen
	$('span#screenTitle').text(game.screenList[screenID].screenDescription)
	
	//Loads the question into the question div
	$('div#question').text(game.screenList[screenID].interQuestion)
	
	//Loads the screens image into the graphics div
	$('div#graphics > img').attr('src', 'game/img/'+game.screenList[screenID].screenImage)
	
	//Clears the textAnswers div and loads the new textAnswers into it
	$('div#textAnswers > ul').empty()
	for(var i = 0; i<game.screenList[screenID].textAnswers.length; i++) {
		$('div#answers ul').append(
			$('<li>').append(
				$('<a/>', {
					onclick: 'loadScreen('+game.screenList[screenID].textAnswers[i][1]+')',
					text: game.screenList[screenID].textAnswers[i][0]
				})
			)
		)
	}
	
	//Clears the imageAnswers div and loads the new imageAnswers into it
	$('map#mainImgMap').empty()
	$.each(game.screenList[screenID].imageAnswers, function(key, imgmap) {
		$('map#mainImgMap').append(
			$('<area/>', {
				shape: "poly",
				coords: imgmap[0],
				href: 'javascript:loadScreen('+imgmap[1]+')',
				style: 'outline: none'
			})
		)
	})
	
	//Loads background music for the current screen
	$('audio#screenBackgroundMusic > source').attr('src','game/mp3/'+game.screenList[screenID].backgroundMusic);
	
	//Loads the sound for the current screen
	$('audio#screenSound > source').attr('src','game/mp3/'+game.screenList[screenID].sound);
	
	//Runs the screen's screenfunc
	game.screenList[screenID].screenfunc()
}
$(function() {
	loadScreen(0);
	
	//Loads background music for the game
	$('audio#gameBackgroundMusic > source').attr('src','game/mp3/'+game.backgroundMusic);
	
	//Sets actions for buttons
	$('img#worldmap').bind('click', function() {
		showWorldmap()
	})
	$('img#save').bind('click', function() {
		showStateMenu()
	})
	$('img#journal').bind('click', function() {
		showJournal()
	})
	$('img#inventory').bind('click', function() {
		showInventory()
	})
	$('img#progression').bind('click', function() {
		showProgression()
	})
})